import React, { useMemo, useRef, useState } from 'react'
import axios from 'axios'
import { NavBar, Input, List, Popup, CheckList, Switch } from 'antd-mobile'
import { DownOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'

// 训练设置页：纯 CSS 的消息提示替代 Toast

const LEVELS = [
  { label: '零基础', desc: '我想开始训练' },
  { label: '初学者', desc: '我每周训练1–2次' },
  { label: '进阶', desc: '我每周训练3–5次' },
  { label: '强化者', desc: '我每周训练5次以上' },
] as const

const EQUIPMENTS = [
  '瑜伽垫',
  '弹力带',
  '哑铃',
  '壶铃',
  '跳绳',
  '泡沫轴',
  '划船机',
  '动感单车',
] as const

const BODY_PARTS = [
  '胸部',
  '背部',
  '肩部',
  '手臂',
  '核心/腹部',
  '臀部',
  '大腿前侧',
  '大腿后侧',
  '小腿',
  '全身',
] as const

export default function SetupTraining() {
  const navigate = useNavigate()

  const [name, setName] = useState('')
  const [level, setLevel] = useState<string>('')
  const [equipments, setEquipments] = useState<string[]>([])
  const [parts, setParts] = useState<string[]>([])
  const [needWarmup, setNeedWarmup] = useState<boolean>(false)
  const [needStretch, setNeedStretch] = useState<boolean>(false)

  const [equipPopup, setEquipPopup] = useState(false)
  const [partPopup, setPartPopup] = useState(false)

  // 纯 CSS 消息（气泡）
  const [msg, setMsg] = useState<{ content: string; type: 'success' | 'fail' | 'warn' } | null>(null)
  const hideTimer = useRef<number | null>(null)
  const showMsg = (content: string, type: 'success' | 'fail' | 'warn' = 'success', duration = 1600) => {
    if (hideTimer.current) {
      window.clearTimeout(hideTimer.current)
      hideTimer.current = null
    }
    setMsg({ content, type })
    hideTimer.current = window.setTimeout(() => {
      setMsg(null)
      hideTimer.current = null
    }, duration)
  }

  const equipSummary = useMemo(() => {
    if (equipments.length === 0) return '未选择'
    if (equipments.length <= 2) return equipments.join('、')
    return `${equipments.length}个器材，${equipments[0]}等`
  }, [equipments])

  const partSummary = useMemo(() => {
    if (parts.length === 0) return '未选择'
    if (parts.length <= 2) return parts.join('、')
    return `${parts.length}个部位，${parts[0]}等`
  }, [parts])

  const submit = async () => {
    if (!name.trim()) {
      showMsg('请先填写训练名称', 'warn')
      return
    }
    if (!level) {
      showMsg('请选择级别', 'warn')
      return
    }

    const payload = {
      name: name.trim(),
      level,
      equipments,
      parts,
      warmup: needWarmup,
      stretch: needStretch,
      createdAt: Date.now(),
    }

    try {
      // 优先通过 Vite 代理提交
      try {
        await axios.post('/api/mytrainings', payload, { headers: { 'Content-Type': 'application/json' } })
      } catch (err) {
        // 若代理未生效，回退直连后端（开发环境）
        await axios.post('http://localhost:5000/api/mytrainings', payload, { headers: { 'Content-Type': 'application/json' } })
      }
      showMsg('添加成功', 'success')
      // 延迟返回，给用户时间看到提示
      window.setTimeout(() => navigate(-1), 500)
    } catch (e: any) {
      console.error('提交 mytrainings 失败:', e?.response?.data || e?.message || e)
      showMsg('保存失败，请稍后重试', 'fail')
    }
  }

  return (
    <div className="setup-page">
      <NavBar onBack={() => navigate(-1)} backArrow style={{ background: 'rgb(227, 83, 26)', color: '#fff' }}>
        创建训练
      </NavBar>

      <div className="container">
        <List header={null}>
          <List.Item>
            <div className="field">
              <div className="label">训练名称</div>
              <Input placeholder="这里输入训练名称" value={name} onChange={setName} clearable />
            </div>
          </List.Item>

          <List.Item>
            <div className="label">选择级别</div>
            <div className="levels">
              {LEVELS.map((lv) => (
                <div
                  key={lv.label}
                  className={`level-card ${level === lv.label ? 'active' : ''}`}
                  onClick={() => setLevel(lv.label)}
                >
                  <div className={`level-title ${level === lv.label ? 'on' : ''}`}>{lv.label}</div>
                  <div className="level-desc">{lv.desc}</div>
                </div>
              ))}
            </div>
          </List.Item>

          <List.Item onClick={() => setEquipPopup(true)} arrow={<DownOutline />} extra={<span className="extra">{equipSummary}</span>}>
            选择器材
          </List.Item>

          <List.Item onClick={() => setPartPopup(true)} arrow={<DownOutline />} extra={<span className="extra">{partSummary}</span>}>
            选择训练部位
          </List.Item>

          <List.Item>
            <div className="switch-row">
              <span>包括热身</span>
              <Switch
                checked={needWarmup}
                onChange={(v) => setNeedWarmup(v)}
                style={{ '--checked-color': 'rgb(229, 80, 26)' } as any}
              />
            </div>
          </List.Item>

          <List.Item>
            <div className="switch-row">
              <span>包括拉伸</span>
              <Switch
                checked={needStretch}
                onChange={(v) => setNeedStretch(v)}
                style={{ '--checked-color': 'rgb(229, 80, 26)' } as any}
              />
            </div>
          </List.Item>
        </List>

        <div className="footer">
          <button className="btn-primary" onClick={submit}>下一步</button>
        </div>
      </div>

      {/* 选择器材弹层（点遮罩关闭） */}
      <Popup visible={equipPopup} onMaskClick={() => setEquipPopup(false)} bodyStyle={{ borderTopLeftRadius: 12, borderTopRightRadius: 12 }}>
        <div className="popup">
          <div className="popup-title">选择器材</div>
          <CheckList multiple value={equipments} onChange={(v) => setEquipments(v as string[])}>
            {EQUIPMENTS.map((e) => (
              <CheckList.Item key={e} value={e}>
                <span className="rainbow-orange">{e}</span>
              </CheckList.Item>
            ))}
          </CheckList>
        </div>
      </Popup>

      {/* 选择训练部位弹层（点遮罩关闭） */}
      <Popup visible={partPopup} onMaskClick={() => setPartPopup(false)} bodyStyle={{ borderTopLeftRadius: 12, borderTopRightRadius: 12 }}>
        <div className="popup">
          <div className="popup-title">选择训练部位</div>
          <CheckList multiple value={parts} onChange={(v) => setParts(v as string[])}>
            {BODY_PARTS.map((p) => (
              <CheckList.Item key={p} value={p}>
                <span className="rainbow-orange">{p}</span>
              </CheckList.Item>
            ))}
          </CheckList>
        </div>
      </Popup>

      {/* 纯 CSS 消息气泡 */}
      {msg && (
        <div className={`msg-bubble ${msg.type}`}>
          {msg.content}
        </div>
      )}

      <style>{`
        .setup-page { --adm-color-primary: rgb(229, 80, 26); min-height: 100vh; }
        /* 背景图片（public/2.png）+ 极浅蒙版 */
        .setup-page {
          background-image:
            linear-gradient(180deg, rgba(255,255,255,0.75) 0%, rgba(255,255,255,0.75) 100%),
            url('/2.png');
          background-size: cover;
          background-position: center;
          background-attachment: fixed;
        }
        /* 列表与条目透明、无边框 */
        .container { padding: 12px 12px 80px; background: transparent; }
        .adm-list, .adm-list-body, .adm-list-body-inner, .adm-list-item, .adm-list-item-content { background: transparent !important; }
        .adm-list-item::after { display: none; }
        /* 标题与输入透明、无描边 */
        .field .label { margin-bottom: 6px; font-weight: 600; color: #222; }
        .adm-input, .adm-input-element, .adm-input-element input { background: transparent !important; border: none !important; }
        /* 级别卡片透明且无边框，仅通过文字高亮表示选择 */
        .levels { display: grid; grid-template-columns: 1fr; gap: 10px; }
        .level-card { border-radius: 12px; background: transparent; border: 1px solid transparent; padding: 12px; }
        .level-card.active { border-color: transparent; box-shadow: none; }
        .level-title { font-weight: 700; margin-bottom: 4px; color: #222; }
        .level-title.on { color: rgb(229, 80, 26); }
        .level-desc { color: #333; font-size: 12px; }
        /* 右侧摘要文本 */
        .extra { color: #333; }
        /* 开关区域只保留开关（滑块）本身视觉，容器透明 */
        .switch-row { display: flex; align-items: center; justify-content: space-between; }
        /* 底部区域透明，按钮用纯 CSS 风格 */
        .footer { position: fixed; left: 0; right: 0; bottom: 0; padding: 12px; background: transparent; box-shadow: none; }
        .btn-primary { width: 100%; height: 44px; border: none; border-radius: 999px; background: rgb(229,80,26); color: #fff; font-weight: 600; letter-spacing: .5px; }
        .btn-primary:active { transform: scale(0.995); }
        /* 弹层内容透明（仅保留文字），并设置主色为橙色使勾选 √ 为橙色 */
        .adm-popup-body { background: transparent !important; }
        .popup { padding: 12px; background: transparent; --adm-color-primary: rgb(227, 83, 26); }
        .popup-title { font-weight: 700; font-size: 16px; margin-bottom: 8px; }
        .adm-check-list, .adm-check-list-item, .adm-check-list-item-content { background: transparent !important; }
        .adm-check-list-item::after { display: none; }
        /* 进一步保险：直接覆盖复选框选中样式为橙色 */
        .popup .adm-checkbox .adm-checkbox-icon-checked { background-color: rgb(227,83,26) !important; border-color: rgb(227,83,26) !important; }
        .popup .adm-checkbox .adm-checkbox-icon { border-color: rgba(0,0,0,0.25); }
        /* 五颜六色的橙色：使用多段橙色渐变作为文字填充 */
        .rainbow-orange {
          background: linear-gradient(90deg,
            #ffb199 0%,
            #ff9966 14%,
            #ff8a3d 28%,
            #ff7a1f 42%,
            #ff6a00 56%,
            #ff8a3d 70%,
            #ff9966 84%,
            #ffb199 100%
          );
          -webkit-background-clip: text;
          background-clip: text;
          color: transparent;
          font-weight: 600;
        }
        /* 纯 CSS 消息气泡 */
        .msg-bubble { position: fixed; left: 50%; top: 50px; transform: translateX(-50%); padding: 10px 14px; border-radius: 999px; color: #fff; font-size: 14px; font-weight: 600; box-shadow: 0 8px 24px rgba(0,0,0,.18); animation: msg-in .2s ease; z-index: 9999; }
        .msg-bubble.success { background: rgba(229,80,26, .95); }
        .msg-bubble.warn { background: rgba(255,193,7, .95); color: #222; }
        .msg-bubble.fail { background: rgba(220,53,69, .95); }
        @keyframes msg-in { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translate(-50%, 0); } }
        /* 顶部导航维持品牌色 */
        .setup-page .adm-nav-bar, .setup-page .adm-nav-bar-title, .setup-page .adm-nav-bar-left, .setup-page .adm-nav-bar-right { color: #fff; }

        @media (min-width: 560px) { .levels { grid-template-columns: 1fr 1fr; } }
      `}</style>
    </div>
  )
}
